#!/usr/bin/env python
#
# Copyright 2008 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import forms
import models
from controllers import handlers


# Note that self.template_vals is being generated on instantiation by the
# parent class, for the handlers below

class GroupListHandler(handlers.AppHandler):

  def get(self):
    memberships = models.GroupMembership.all().filter("person =", models.Person.GetPerson()).fetch(100)
    if len(memberships) == 0:
      self.template_vals["group_list"] = []
    else: 
      self.template_vals["group_list"] = [mem.group.data() for mem in memberships]
    html = self.app_render('group_list.html', self.template_vals)
    if self.request.get("html"):
      html = self.app_render('group_list.html', self.template_vals)
      self.response.out.write(html)
    else:
      callback = self.request.get("callback")
      jsonp = handlers.jsonp_render(self.template_vals, callback)
      self.response.out.write(jsonp)

class GroupCreateHandler(handlers.AppHandler):

  def WritePage(self, form=None):
    form = form or forms.GroupForm()  # shorter than if not form: form = ...
    self.template_vals["group_create_form"] = form.as_table()
    html = self.app_render('group_create.html', self.template_vals)
    self.response.out.write(html)

  def ProcessCreateRpc(self, multi_dict):
    name = multi_dict.get("name")
    currency = multi_dict.get("currency")
    owner = models.Person.GetPerson()
    group = models.Group(name=name, currency=currency, owner=owner)
    self.response.out.write(models.Group.create_group(group))

  def get(self):
    if self.request.get("html"):
      self.WritePage()
    else:
      self.ProcessCreateRpc(self.request.GET)

  def post(self):
    submitted_form = forms.GroupForm(data=self.request.POST)
    if submitted_form.is_valid():
      owner = models.Person.GetPerson()
      new_group = models.Group(name=self.request.get("name"),
                               owner=owner,
                               currency=self.request.get("currency"))
      models.Group.create_group(new_group, owner)
      # call helper function to populate owner, create group and membership
      self.redirect("/?msg=success")
    else:
      self.WritePage(form=submitted_form)

class GroupDetailHandler(handlers.AppHandler):

  def get(self):
    group_id = int(self.request.get("id"))  # cast to int
    group = models.Group.get_by_id(group_id)
    self.template_vals["group"] = group.data()
    if (self.request.get("html")):
      html = self.app_render('group_detail.html', self.template_vals)
      self.response.out.write(html)
    else:
      callback = self.request.get("callback")
      jsonp = handlers.jsonp_render(self.template_vals, callback)
      self.response.out.write(jsonp)

class AddMemberHandler(handlers.AppHandler):

  def AddMember(self):
    nickname = self.request.get("nickname")
    email_addr = self.request.get("email")
    group_id = None
    try:
      group_id = int(self.request.get("group_id"))  # cast to int
    except:
      pass
    if not (email_addr and group_id): pass  # TODO: redirect with error
    user = users.User(email_addr)
    person = models.Person.GetPerson(user)
    group = models.Group.get_by_id(group_id)
    return group.add_member(person, nickname)

  def get(self):
    self.response.out.write(self.AddMember())

  def post(self):
    self.AddMember()
    self.redirect(self.request.referrer + "&msg=Added+" + self.request.get("email"))


class ListTransactionsHandler(handlers.AppHandler):

  def get(self):
    group_id = None
    try:
      group_id = int(self.request.get("id"))  # cast to int
    except:
      self.redirect(self.request.referrer)
      return
    group = models.Group.get_by_id(group_id)
    txn_list = models.Transaction.all().filter(
        "group =", group.key()).order("-txn_date").fetch(100)
    self.template_vals["transaction_list"] = txn_list
    html = self.app_render('group_transactions_list.html', self.template_vals)
    self.response.out.write(html)
